<template>
  <div class="admin">
    <div class="admin-title">{{ t("shippingAddress.title") }}</div>

    <div class="toolbar">
      <el-button type="primary" @click="openCreate">{{ t("shippingAddress.create") }}</el-button>
      <span class="tips"
        >{{ t("shippingAddress.tips", { count: list.length, max: maxAddressCount }) }}</span
      >
    </div>

    <div class="addr-list">
      <el-card
        v-for="item in list"
        :key="item.id"
        class="addr-item"
        shadow="never"
      >
        <div class="addr-item__hd">
          <div class="receiver">
            <span class="name">{{ item.receiver }}</span>
            <el-tag
              v-if="item.isDefault"
              size="small"
              type="success"
              effect="plain"
              >{{ t("shippingAddress.defaultTag") }}</el-tag
            >
            <el-button
              v-else
              size="small"
              text
              type="primary"
              @click="setDefault(item)"
              >{{ t("shippingAddress.setDefault") }}</el-button
            >
          </div>
          <div class="ops">
            <el-button link type="primary" @click="openEdit(item)"
              >{{ t("shippingAddress.edit") }}</el-button
            >
            <el-button
              link
              type="danger"
              :disabled="item.isDefault && list.length === 1"
              @click="confirmRemove(item)"
              >{{ t("shippingAddress.delete") }}</el-button
            >
          </div>
        </div>

        <el-descriptions :column="3" border size="small" class="addr-desc">
          <el-descriptions-item :label="t('shippingAddress.receiver')">
            {{ item.receiver }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('shippingAddress.phone')">
            {{ maskPhone(item.mobile) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('shippingAddress.email')">
            {{ maskEmail(item.email) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('shippingAddress.region')" :span="2">
            {{ formatRegion(item.region) }}
          </el-descriptions-item>
          <el-descriptions-item :label="t('shippingAddress.address')" :span="3">
            {{ item.address }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>

    <el-dialog
      v-model="formVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item :label="t('shippingAddress.receiver')" prop="receiver">
          <el-input v-model="formModel.receiver" maxlength="30" clearable />
        </el-form-item>
        <el-form-item :label="t('shippingAddress.region')" prop="region">
          <el-cascader
            v-model="formModel.region"
            :options="regionOptions"
            clearable
            :placeholder="t('shippingAddress.regionPlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="t('shippingAddress.address')" prop="address">
          <el-input v-model="formModel.address" maxlength="100" clearable />
        </el-form-item>
        <el-form-item :label="t('shippingAddress.phone')" required>
          <div class="phone-inline">
            <el-input
              v-model="formModel.areaCode"
              :placeholder="t('shippingAddress.areaCodePlaceholder')"
              maxlength="4"
              clearable
            />
            <el-input
              v-model="formModel.mobile"
              :placeholder="t('shippingAddress.mobilePlaceholder')"
              maxlength="11"
              clearable
            />
          </div>
        </el-form-item>
        <el-form-item :label="t('shippingAddress.email')" prop="email">
          <el-input v-model="formModel.email" clearable />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-tag class="hk-only" effect="plain" type="warning"
            >{{ t("shippingAddress.regionTips") }}</el-tag
          >
          <div class="actions">
            <el-button @click="formVisible = false">{{ t("shippingAddress.cancel") }}</el-button>
            <el-button @click="saveAddress(true)">{{ t("shippingAddress.saveAndDefault") }}</el-button>
            <el-button type="primary" @click="saveAddress(false)"
              >{{ t("shippingAddress.save") }}</el-button
            >
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";

definePageMeta({
  title: "收货地址",
  en_title: "Shipping address",
  zh_hk_title: "收穫地址",
  ssr: true,
  isTokenCheck: true,
});

const { t } = useI18n();
const maxAddressCount = 10;

const list = ref([
  {
    id: 1,
    receiver: "舒sir",
    region: ["hong_kong", "kowloon", "yau_tsim_mong"],
    address: "万同里 八区 1号楼",
    areaCode: "852",
    mobile: "1380000711",
    email: "am***i@163.com",
    isDefault: true,
  },
  {
    id: 2,
    receiver: "舒sir",
    region: ["hong_kong", "new_territories", "tsuen_wan"],
    address: "万同里 八区 1号楼",
    areaCode: "852",
    mobile: "1380000711",
    email: "am***i@163.com",
    isDefault: false,
  },
  {
    id: 3,
    receiver: "舒sir",
    region: ["hong_kong", "hong_kong_island", "central_western"],
    address: "万同里 八区 1号楼",
    areaCode: "852",
    mobile: "1380000711",
    email: "am***i@163.com",
    isDefault: false,
  },
]);

const regionOptions = computed(() => [
  {
    value: "hong_kong",
    label: t("shippingAddress.regions.hongKong"),
    children: [
      {
        value: "hong_kong_island",
        label: t("shippingAddress.regions.hongKongIsland"),
        children: [
          { value: "central_western", label: t("shippingAddress.regions.centralWestern") },
          { value: "wan_chai", label: t("shippingAddress.regions.wanChai") },
        ],
      },
      {
        value: "kowloon",
        label: t("shippingAddress.regions.kowloon"),
        children: [
          { value: "yau_tsim_mong", label: t("shippingAddress.regions.yauTsimMong") },
          { value: "sham_shui_po", label: t("shippingAddress.regions.shamShuiPo") },
        ],
      },
      {
        value: "new_territories",
        label: t("shippingAddress.regions.newTerritories"),
        children: [
          { value: "tsuen_wan", label: t("shippingAddress.regions.tsuenWan") },
          { value: "sha_tin", label: t("shippingAddress.regions.shaTin") },
        ],
      },
    ],
  },
]);

const regionLabelMap = computed(() => {
  const map = {};
  const traverse = (nodes = []) => {
    nodes.forEach((item) => {
      map[item.value] = item.label;
      if (item.children) {
        traverse(item.children);
      }
    });
  };
  traverse(regionOptions.value || []);
  return map;
});

const formVisible = ref(false);
const formRef = ref(null);
const formModel = reactive(emptyForm());

const dialogTitle = computed(() =>
  formModel.id ? t("shippingAddress.editTitle") : t("shippingAddress.createTitle")
);

const rules = computed(() => ({
  receiver: [{ required: true, message: t("shippingAddress.rules.receiver"), trigger: "blur" }],
  region: [{ required: true, message: t("shippingAddress.rules.region"), trigger: "change" }],
  address: [{ required: true, message: t("shippingAddress.rules.address"), trigger: "blur" }],
  email: [{ type: "email", message: t("shippingAddress.rules.email"), trigger: "blur" }],
}));

function emptyForm() {
  return {
    id: 0,
    receiver: "",
    region: [],
    address: "",
    areaCode: "852",
    mobile: "",
    email: "",
    isDefault: false,
  };
}

function maskPhone(p) {
  if (!p) return "";
  return p.replace(/^(\d{3})\d+(\d{3})$/, "$1***$2");
}

function maskEmail(e) {
  if (!e) return "";
  const parts = e.split("@");
  const name = parts[0] || "";
  const domain = parts[1] || "";
  return `${name.slice(0, 2)}***@${domain}`;
}

function formatRegion(region = []) {
  const map = regionLabelMap.value || {};
  return (region || [])
    .map((code) => map[code] || code)
    .join(" / ");
}

function openCreate() {
  Object.assign(formModel, emptyForm());
  formVisible.value = true;
}

function openEdit(item) {
  Object.assign(formModel, JSON.parse(JSON.stringify(item)));
  formVisible.value = true;
}

function saveAddress(setAsDefault = false) {
  if (!formRef.value) return;
  formRef.value.validate((valid) => {
    if (!valid) return;

    if (list.value.length >= maxAddressCount && !formModel.id) {
      ElMessage.warning(t("shippingAddress.messages.maxLimit", { max: maxAddressCount }));
      return;
    }

    const newItem = JSON.parse(JSON.stringify(formModel));

    if (formModel.id) {
      const idx = list.value.findIndex((x) => x.id === formModel.id);
      if (idx > -1) list.value[idx] = newItem;
    } else {
      newItem.id = Date.now();
      list.value.unshift(newItem);
    }

    if (setAsDefault) {
      list.value.forEach((x) => (x.isDefault = x.id === newItem.id));
      ElMessage.success(t("shippingAddress.messages.saveAndDefaultSuccess"));
    } else {
      ElMessage.success(
        formModel.id ? t("shippingAddress.messages.saveSuccess") : t("shippingAddress.messages.createSuccess")
      );
    }

    formVisible.value = false;
  });
}

function setDefault(item) {
  list.value.forEach((x) => (x.isDefault = x.id === item.id));
  ElMessage.success(t("shippingAddress.messages.setDefaultSuccess"));
}

function confirmRemove(item) {
  ElMessageBox.confirm(t("shippingAddress.messages.deleteConfirm"), t("shippingAddress.messages.deleteTitle"), {
    confirmButtonText: t("shippingAddress.messages.confirm"),
    cancelButtonText: t("shippingAddress.messages.cancel"),
    type: "warning",
  })
    .then(() => {
      list.value = list.value.filter((x) => x.id !== item.id);
      ElMessage.success(t("shippingAddress.messages.deleteSuccess"));
    })
    .catch(() => {
      // 用户取消删除
    });
}
</script>

<style lang="less" scoped>
.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 12px 0 16px;

  .tips {
    color: #909399;
    font-size: 12px;
  }
}

.addr-list {
  display: flex;
  flex-direction: column;
  gap: 12px;

  .addr-item {
    border: 1px solid #ebeef5;

    &__hd {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 6px;

      .receiver {
        display: flex;
        align-items: center;
        font-weight: 600;

        :deep(.el-tag),
        .el-button {
          margin-left: 8px;
        }
      }

      .ops {
        .el-button + .el-button {
          margin-left: 8px;
        }
      }
    }
  }
}

.addr-desc {
  :deep(.el-descriptions__label) {
    width: 90px;
    color: #909399;
  }
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .actions {
    .el-button + .el-button {
      margin-left: 8px;
    }
  }

  .hk-only {
    margin-right: 12px;
  }
}

// 新增样式，统一表单元素宽度并增加右边距
:deep(.el-form) {
  .el-form-item__content {
    width: 100%;
    margin-right: 40px; // 增加右边距

    .el-input,
    .el-cascader {
      width: 100% !important;
    }
  }
}
.phone-inline {
  display: flex;
  gap: 8px;
  width: 100%;

  :deep(.el-input) {
    width: auto !important;
  }

  // 区号更短一些
  :deep(.el-input:first-child) {
    flex: 0 0 120px !important; // 增加区号输入框宽度
  }
  // 电话号码占满剩余空间
  :deep(.el-input:last-child) {
    flex: 1 1 auto;
    min-width: 0;
  }
}
</style>
